package com.adms.websocket;

import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.adms.domain.Message;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class WebSocketServer extends TextWebSocketHandler {
	
	@Autowired
	private ObjectMapper objectMapper;

	private final Map<WebSocketSession,Integer > connections = new ConcurrentHashMap<>();


	/**
	 * 建立连接
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		Principal principal = session.getPrincipal();
		if(principal != null) {
			connections.put(session,Integer.valueOf(principal.getName()));
		}
	}

	/**
	 * 断开连接
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		connections.remove(session);
	}

	/**
	 * 处理消息
	 */
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		broadcast(session, message);
	}

	private void broadcast(WebSocketSession session, TextMessage message) {
		for (WebSocketSession s : connections.keySet()) {
			try {
				s.sendMessage(message);
			} catch (Exception e) {
				connections.remove(s);
				try {
					s.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}


	public void sendMessage(Integer userId, Message message) {
		TextMessage textMessage = null;
		try {
			textMessage = new TextMessage(objectMapper.writeValueAsString(message));
		} catch (JsonProcessingException e2) {
			e2.printStackTrace();
		}
		if(textMessage != null) {
			WebSocketSession s;
			Integer existUserId;
			for(Entry<WebSocketSession, Integer> entry:connections.entrySet()) {
				s = entry.getKey();
				existUserId = entry.getValue();
				if(existUserId.equals(userId)) {
					try {
						s.sendMessage(textMessage);
					} catch (IOException e) {
						connections.remove(s);
						try {
							s.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		}
	}
}